<?php


namespace common\services;


use common\helpers\Util;

class HuaXinService
{

    public  function sendSms($mobile,$content='')
    {
        $params = \Yii::$app->params;
        if(!$params['cshx_send_url']  || !$params['cshx_user_id'] || !$params['cshx_account'] || !$params['cshx_api_password']) {
            throw new \Exception('短信发送失败，请确认短信配置信息');
        }
        $cshxSendUrl = $params['cshx_send_url'];
        $data = [
            'userid' => $params['cshx_user_id'],
            'account' => trim($params['cshx_account']),
            'password' => strtoupper(md5(trim($params['cshx_api_password']))),
            'mobile' => $mobile,
            'content' => $content,
            'sendTime' => '',
            'action' => 'send',
            'extno' => ''
        ];


        $info = $this->doPost($cshxSendUrl, $data);

        //$info = '{"returnstatus":"Success","message":"操作成功","remainpoint":"115800","taskID":"1808284157386407","successCounts":"1"}';
        $infoArr = json_decode($info, true);
        //记录发送记录
        if (isset($infoArr['returnstatus']) && $infoArr['returnstatus'] == 'Success') {
            return true;
        } else {
            return false;
        }
    }



    /**
     * curl 发送请求
     *
     **/
    private function doPost($url, $postData)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // we are doing a POST request
        curl_setopt($ch, CURLOPT_POST, 1);
        // adding the post variables to the request
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


}